<!-- 点击reference弹出的窗口 -->
<template>
  <el-dialog
    width="70%"
    class="parameter-select-reference"
    v-bind="$attrs"
    :title="$t('flyparam.select_reference_table')"
    v-on="$listeners"
    @open="handleOpen"
    @close="handleClose"
  >
    <div class="p-3 inline-block">
      <div class="flex items-center">
        <el-input
          v-model="label"
          size="small mr-[10]"
          :maxlength="MAX_LENGTH.LABEL"
          :placeholder="$t('flyparam.entry_label')"
          @keyup.enter.native="
            () => {
              label = label.trim()
              search()
            }
          "
          @blur="() => (label = label.trim())"
        />
        <el-button
          type="primary"
          class="align-middle p-1.5"
          size="small"
          @click="search"
        >
          <svg-icon icon-class="search" class="text-lg" />
        </el-button>
      </div>
    </div>
    <el-card
      :body-style="{ padding: '0', boderRadius: 0, border: 'none' }"
       
      shadow="never"
      :current-page="pageNo"
      :page-size="pageSize"
      :total="total"
      @current-change="currentChangeHandle"
    >
      <el-table
        ref="table"
        v-loading="loading"
        :data="tableData"
        :row-key="
          (row) => {
            return row.$label
          }
        "
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="50"
          :reserve-selection="true"
        />
        <el-table-column
          v-for="col in columns"
          :key="col.key"
          :label="col.label"
          :prop="col.key"
          min-width="200"
          :show-overflow-tooltip="true"
        />
      </el-table> </el-card
    ><template #footer>
      <div>
        <el-button type="primary" size="small" @click="confirm">{{
          $t('common.confirm')
        }}</el-button>
      </div></template
    >
  </el-dialog>
</template>

<script>
import { getReferenceEntryRecord } from '@/api/parameter'
import { isObjectBoolean } from '@/utils'
import { MAX_LENGTH } from '../constant'

export default {
  inheritAttrs: false,
  props: ['tableId', 'templateId', 'currentItem', 'hasParam', 'dryrun'],
  data() {
    return {
      MAX_LENGTH: Object.freeze(MAX_LENGTH),
      loading: false,
      tableData: [],
      columns: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      selections: [],
      currentPageChange: false,
      selectedItemsByPage: [],
      label: ''
    }
  },
  mounted() {
    // this.fetchReferenceEntryRecord()
  },
  methods: {
    search() {
      this.pageNo = 1
      this.fetchReferenceEntryRecord()
    },
    fetchReferenceEntryRecord() {
      this.loading = true
      getReferenceEntryRecord(this.templateId, this.tableId, {
        rowUniqueKeyLike: this.label,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      })
        .then((data) => {
          this.total = data.total
          this.columns = data.columns.filter((col) => col.key !== '$id')
          this.tableData = data.items.map((item) => {
            const keys = Object.keys(item)
            const ret = {}
            for (let i = 0; i < keys.length; i++) {
              const key = keys[i]
              ret[key] =
                isObjectBoolean(item[key][0]) || item[key][0]
                  ? String(item[key][0])
                  : ''
            }
            return ret
          })
          this.$nextTick(() => {
            let arr = []
            // TODO: 需要优化
            if (this.dryrun) {
              arr = this.currentItem.value || []
            } else {
              if (this.hasParam) {
                arr = this.currentItem.paramValues
              } else {
                arr = this.currentItem.defaultValues
              }
            }
            this.tableData.map((item, index) => {
              arr.map((label) => {
                if (item.Label == label) {
                  this.$refs.table.toggleRowSelection(
                    this.tableData[index],
                    true
                  )
                }
                // const row = this.tableData.find((data) => data.label === label)
                // this.$refs.table.toggleRowSelection(row, true)
              })
            })
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    currentChangeHandle(val) {
      this.pageNo = val
      this.fetchReferenceEntryRecord()
      this.currentPageChange = true
    },
    handleOpen() {
      this.fetchReferenceEntryRecord()
    },
    // 当表格选项发生变化时触发该函数
    handleSelectionChange(val) {
      console.log(val)
      // if (this.currentPageChange) {
      //   this.currentPageChange = false
      // } else {
      //   // this.selectedItemsByPage[this.pageNo - 1] = val
      this.selections = val
      // }
    },
    confirm() {
      const labels = this.selections.map((item) => item.$label)
      if (labels.length > this.currentItem.maxLength) {
        return this.$message.error(
          `The length exceeds. (Max length: ${this.currentItem.maxLength})`
        )
      }
      if (this.hasParam) {
        this.currentItem.paramValues = labels
      } else {
        this.currentItem.defaultValues = labels
      }
      this.$emit('confirm', labels, this.selections)
      this.$emit('update:model-value', false)
    },
    handleClose() {
      this.$refs.table.clearSelection()
      Object.assign(this.$data, this.$options.data())
    },
    handleRowClick(row, column, event) {
      let select = true
      if (this.selections.some((item) => item.id === row.id)) {
        select = false
      }
      this.$refs.table.toggleRowSelection(row, select)
    }
  }
}
</script>

<style lang="scss">
.parameter-select-reference {
  .el-dialog__body {
    padding: 0 !important;
  }
}
</style>

